import {addSurplus} from "./api";
import qs from "qs";
import { Notification } from 'element-ui';
import store from "../store";

const dailyActivities=(key,type,time=5000,m_id)=>{
    let timeout = setTimeout(()=>{
        if(type==5 && store.state.sign){
            /*签到功能特殊处理，他能否签到，会通过后端实时更新，只要后端说可以*/
            PostDailyActivities(type,key,m_id)
            return
        }
        let localStorageValue = localStorage.getItem(key)
        if(!localStorageValue){
            PostDailyActivities(type,key)
        }else{
            if(new Date().getDate()!=new Date(localStorageValue-0).getDate()){
                /*不是同一天*/
                PostDailyActivities(type,key)
            }else{
                /*同一天 进一步判断是否为当天*/
                if(!(localStorageValue-0>=new Date(new Date().setDate(new Date().getDate())).setHours(0,0,0,0) && localStorageValue-0<new Date(new Date().setDate(new Date().getDate()+1)).setHours(0,0,0,0))){
                    PostDailyActivities(type,key)
                }
            }
        }
    },time)
    return timeout
}

const PostDailyActivities = (type,key,m_id) => {
    addSurplus(qs.stringify({type,m_id})).then(res=>{
        localStorage.setItem(key,new Date().getTime()+'')
        if(res?.status == 200){
            if(type == 5){
                store.commit('setSign',false);
            }
            Notification.success({
                title:res?.msg,
                message:`获得奖励￥${res?.body}元`
            })
        }else{
            Notification.error({
                title:'每日奖励活动——警告',
                message:res?.msg,
            })
        }
    }).catch(err=>{
        console.log(err)
    })
}

const sleep = (time) => {
  return new Promise((resolve,reject) => {
      setTimeout(resolve,time)
  })
}

export {dailyActivities,sleep}
